﻿using System.Reflection;

namespace Api.Shared.Utils
{
    public static class MyCopyProperty
    {
        //public static void CopyProperties(object source, object destination)
        //{
        //    if (source == null || destination == null)
        //    {
        //        return;
        //    }

        //    Type sourceType = source.GetType();
        //    Type targetType = destination.GetType();

        //    foreach (PropertyInfo sourceProperty in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        //    {
        //        PropertyInfo targetProperty = targetType.GetProperty(sourceProperty.Name);
        //        if (targetProperty != null && targetProperty.CanWrite && sourceProperty.PropertyType == targetProperty.PropertyType)
        //        {
        //            targetProperty.SetValue(destination, sourceProperty.GetValue(source));
        //        }
        //    }
        //}

        public static void CopyProperties(object source, object destination)
        {
            if (source == null || destination == null)
            {
                return;
            }

            Type sourceType = source.GetType();
            Type targetType = destination.GetType();

            foreach (PropertyInfo sourceProperty in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                PropertyInfo targetProperty = targetType.GetProperty(sourceProperty.Name);
                if (targetProperty != null && targetProperty.CanWrite)
                {
                    object sourceValue = sourceProperty.GetValue(source);

                    if (sourceValue != null && sourceProperty.PropertyType == typeof(float))
                    {
                        // 对于 float 类型的属性，使用 Math.Round 保留两位小数
                        // 注意：Math.Round 返回 double，需要转换为 float
                        float roundedValue = (float)Math.Round((float)sourceValue, 2);
                        targetProperty.SetValue(destination, roundedValue);
                    }
                    else if (sourceProperty.PropertyType == targetProperty.PropertyType)
                    {
                        // 对于其他类型，直接复制值
                        targetProperty.SetValue(destination, sourceValue);
                    }
                    // 如果源属性和目标属性的类型不匹配，则不复制该属性的值
                }
            }
        }
    }
}
